#!/usr/bin/env bash
scriptVersion="1.8"
scriptName="AutoConfig"

#### Import Settings
source /config/extended.conf
#### Import Functions
source /config/extended/functions
#### Create Log File
logfileSetup

if [ "$enableAutoConfig" != "true" ]; then
	log "Script is not enabled, enable by setting enableAutoConfig to \"true\" by modifying the \"/config/extended.conf\" config file..."
	log "Sleeping (infinity)"
	sleep infinity
fi

getArrAppInfo
verifyApiAccess

if [ -f /config/extended/naming.json ]; then
	log "Using custom Sonarr Naming (/config/extended/naming.json)..."
	namingJson=$(cat /config/extended/naming.json)
else
	log "Getting Trash Guide Recommended Naming..."
	namingJson=$(curl -s "https://raw.githubusercontent.com/TRaSH-/Guides/master/docs/json/sonarr/naming/sonarr-naming.json")
fi

standardNaming=$(echo "$namingJson" | jq -r '.episodes.standard."default:4"')
dailyNaming=$(echo "$namingJson" | jq -r '.episodes.daily."default:4"')
animeNaming=$(echo "$namingJson" | jq -r '.episodes.anime."default:4"')
seriesNaming=$(echo "$namingJson" | jq -r '.series.default')
seasonNaming=$(echo "$namingJson" | jq -r '.season.default')

if [ "$configureNaming" == "true" ] || [ -z "$configureNaming" ]; then
	log "Updating Sonarr File Naming..."
	updateArr=$(curl -s "$arrUrl/api/v3/config/naming" -X PUT -H "Content-Type: application/json" -H "X-Api-Key: $arrApiKey" --data-raw "{
		\"renameEpisodes\":true,
		\"replaceIllegalCharacters\":true,
		\"multiEpisodeStyle\":5,
		\"standardEpisodeFormat\":\"$standardNaming\",
		\"dailyEpisodeFormat\":\"$dailyNaming\",
		\"animeEpisodeFormat\":\"$animeNaming\",
		\"seriesFolderFormat\":\"$seriesNaming\",
		\"seasonFolderFormat\":\"$seasonNaming\",
		\"specialsFolderFormat\":\"$seasonNaming\",
		\"includeSeriesTitle\":false,
		\"includeEpisodeTitle\":false,
		\"includeQuality\":false,
		\"replaceSpaces\":true,
		\"separator\":\" - \",
		\"numberStyle\":\"S{season:00}E{episode:00}\",
		\"id\":1
		}")    
	log "Complete"
fi


if [ "$configureMediaManagement" == "true" ] || [ -z "$configureMediaManagement" ]; then
	log "Updating Sonrr Media Management..."
	updateArr=$(curl -s "$arrUrl/api/v3/config/mediamanagement" -X PUT -H "Content-Type: application/json" -H "X-Api-Key: $arrApiKey" --data-raw '{"autoUnmonitorPreviouslyDownloadedEpisodes":false,"recycleBin":"","recycleBinCleanupDays":7,"downloadPropersAndRepacks":"doNotPrefer","createEmptySeriesFolders":false,"deleteEmptyFolders":true,"fileDate":"utcAirDate","rescanAfterRefresh":"always","setPermissionsLinux":false,"chmodFolder":"777","chownGroup":"","episodeTitleRequired":"bulkSeasonReleases","skipFreeSpaceCheckWhenImporting":false,"minimumFreeSpaceWhenImporting":100,"copyUsingHardlinks":true,"useScriptImport":false,"scriptImportPath":"","importExtraFiles":true,"extraFileExtensions":"srt","enableMediaInfo":true,"id":1}')
	log "Complete"
fi

if [ "$configureMetadataProviderSettings" == "true" ] || [ -z "$configureMetadataProviderSettings" ]; then
	log "Updating Sonarr Medata Settings..."
	updateArr=$(curl -s "$arrUrl/api/v3/metadata/1?" -X PUT -H "Content-Type: application/json" -H "X-Api-Key: $arrApiKey" --data-raw '{"enable":true,"name":"Kodi (XBMC) / Emby","fields":[{"name":"seriesMetadata","value":true},{"name":"seriesMetadataEpisodeGuide","value":true},{"name":"seriesMetadataUrl","value":false},{"name":"episodeMetadata","value":true},{"name":"seriesImages","value":true},{"name":"seasonImages","value":true},{"name":"episodeImages","value":true}],"implementationName":"Kodi (XBMC) / Emby","implementation":"XbmcMetadata","configContract":"XbmcMetadataSettings","infoLink":"https://wiki.servarr.com/sonarr/supported#xbmcmetadata","tags":[],"id":1}')
	updateArr=$(curl -s "$arrUrl/api/v3/metadata/4?" -X PUT -H "Content-Type: application/json" -H "X-Api-Key: $arrApiKey" --data-raw '{"enable":true,"name":"Plex","fields":[{"name":"seriesPlexMatchFile","value":true}],"implementationName":"Plex","implementation":"PlexMetadata","configContract":"PlexMetadataSettings","infoLink":"https://wiki.servarr.com/sonarr/supported#plexmetadata","tags":[],"id":4}')
fi

if [ "$configureCustomScripts" == "true" ] || [ -z "$configureCustomScripts" ]; then
	log "Configuring Sonarr Custom Scripts"
	if curl -s "$arrUrl/api/v3/notification" -H "X-Api-Key: ${arrApiKey}" | jq -r .[].name | grep "PlexNotify.bash" | read; then
		log "PlexNotify.bash already added to Sonarr custom scripts"
	else
		log "Adding PlexNotify.bash to Sonarr custom scripts"
	  # Send a command to check file path, to prevent error with adding...
		updateArr=$(curl -s "$arrUrl/api/v3/filesystem?path=%2Fconfig%2Fextended%2Fscripts%2FPlexNotify.bash&allowFoldersWithoutTrailingSlashes=true&includeFiles=true" -H "X-Api-Key: ${arrApiKey}")
	  
	  # Add PlexNotify.bash
	  updateArr=$(curl -s "$arrUrl/api/v3/notification?" -X POST -H "Content-Type: application/json" -H "X-Api-Key: ${arrApiKey}" --data-raw '{"onGrab":false,"onDownload":true,"onUpgrade":true,"onRename":true,"onSeriesDelete":true,"onEpisodeFileDelete":true,"onEpisodeFileDeleteForUpgrade":true,"onHealthIssue":false,"onApplicationUpdate":false,"supportsOnGrab":true,"supportsOnDownload":true,"supportsOnUpgrade":true,"supportsOnRename":true,"supportsOnSeriesDelete":true,"supportsOnEpisodeFileDelete":true,"supportsOnEpisodeFileDeleteForUpgrade":true,"supportsOnHealthIssue":true,"supportsOnApplicationUpdate":true,"includeHealthWarnings":false,"name":"PlexNotify.bash","fields":[{"name":"path","value":"/config/extended/PlexNotify.bash"},{"name":"arguments"}],"implementationName":"Custom Script","implementation":"CustomScript","configContract":"CustomScriptSettings","infoLink":"https://wiki.servarr.com/sonarr/supported#customscript","message":{"message":"Testing will execute the script with the EventType set to Test, ensure your script handles this correctly","type":"warning"},"tags":[]}')
	  log "Complete"
	fi
	
	if curl -s "$arrUrl/api/v3/notification" -H "X-Api-Key: ${arrApiKey}" | jq -r .[].name | grep "DailySeriesEpisodeTrimmer.bash" | read; then
		log "DailySeriesEpisodeTrimmer.bash already added to Sonarr custom scripts"
	else
		log "Adding DailySeriesEpisodeTrimmer.bash to Sonarr custom scripts"
		# Send a command to check file path, to prevent error with adding...
		updateArr=$(curl -s "$arrUrl/api/v3/filesystem?path=%2Fconfig%2Fextended%2Fscripts%2FDailySeriesEpisodeTrimmer.bash&allowFoldersWithoutTrailingSlashes=true&includeFiles=true" -H "X-Api-Key: ${arrApiKey}")
		
		# Add DailySeriesEpisodeTrimmer.bash
		updateArr=$(curl -s "$arrUrl/api/v3/notification?" -X POST -H "Content-Type: application/json" -H "X-Api-Key: ${arrApiKey}" --data-raw '{"onGrab":false,"onDownload":true,"onUpgrade":true,"onRename":true,"onSeriesDelete":true,"onEpisodeFileDelete":false,"onEpisodeFileDeleteForUpgrade":false,"onHealthIssue":false,"onApplicationUpdate":false,"supportsOnGrab":true,"supportsOnDownload":true,"supportsOnUpgrade":true,"supportsOnRename":true,"supportsOnSeriesDelete":true,"supportsOnEpisodeFileDelete":true,"supportsOnEpisodeFileDeleteForUpgrade":true,"supportsOnHealthIssue":true,"supportsOnApplicationUpdate":true,"includeHealthWarnings":false,"name":"DailySeriesEpisodeTrimmer.bash","fields":[{"name":"path","value":"/config/extended/DailySeriesEpisodeTrimmer.bash"},{"name":"arguments"}],"implementationName":"Custom Script","implementation":"CustomScript","configContract":"CustomScriptSettings","infoLink":"https://wiki.servarr.com/sonarr/supported#customscript","message":{"message":"Testing will execute the script with the EventType set to Test, ensure your script handles this correctly","type":"warning"},"tags":[]}')
		log "Complete"
	fi
	
	if curl -s "$arrUrl/api/v3/notification" -H "X-Api-Key: ${arrApiKey}" | jq -r .[].name | grep "Extras.bash" | read; then
		log "Extras.bash already added to Sonarr custom scripts"
	else
		log "Adding Extras.bash to Sonarr custom scripts"
		# Send a command to check file path, to prevent error with adding...
		updateArr=$(curl -s "$arrUrl/api/v3/filesystem?path=%2Fconfig%2Fextended%2Fscripts%2FExtras.bash&allowFoldersWithoutTrailingSlashes=true&includeFiles=true" -H "X-Api-Key: ${arrApiKey}")
		
		# Add Extras.bash
		updateArr=$(curl -s "$arrUrl/api/v3/notification?" -X POST -H "Content-Type: application/json" -H "X-Api-Key: ${arrApiKey}" --data-raw '{"onGrab":false,"onDownload":true,"onUpgrade":true,"onRename":true,"onSeriesDelete":false,"onEpisodeFileDelete":false,"onEpisodeFileDeleteForUpgrade":false,"onHealthIssue":false,"onApplicationUpdate":false,"supportsOnGrab":true,"supportsOnDownload":true,"supportsOnUpgrade":true,"supportsOnRename":true,"supportsOnSeriesDelete":false,"supportsOnEpisodeFileDelete":true,"supportsOnEpisodeFileDeleteForUpgrade":true,"supportsOnHealthIssue":true,"supportsOnApplicationUpdate":true,"includeHealthWarnings":false,"name":"Extras.bash","fields":[{"name":"path","value":"/config/extended/Extras.bash"},{"name":"arguments"}],"implementationName":"Custom Script","implementation":"CustomScript","configContract":"CustomScriptSettings","infoLink":"https://wiki.servarr.com/sonarr/supported#customscript","message":{"message":"Testing will execute the script with the EventType set to Test, ensure your script handles this correctly","type":"warning"},"tags":[]}')
		log "Complete"
	fi
	
	## Tdarr Scan
	if curl -s "$arrUrl/api/v3/notification" -H "X-Api-Key: ${arrApiKey}" | jq -r .[].name | grep "TdarrScan.bash" | read; then
		log "TdarrScan.bash already added to Sonarr custom scripts"
	else
		log "Adding TdarrScan.bash to Sonarr custom scripts"
		# Send a command to check file path, to prevent error with adding...
		updateArr=$(curl -s "$arrUrl/api/v3/filesystem?path=%2Fconfig%2Fextended%2Fscripts%2FTdarrScan.bash&allowFoldersWithoutTrailingSlashes=true&includeFiles=true" -H "X-Api-Key: ${arrApiKey}")
		
		# Add TdarrScan.bash
		updateArr=$(curl -s "$arrUrl/api/v3/notification?" -X POST -H "Content-Type: application/json" -H "X-Api-Key: ${arrApiKey}" --data-raw '{"onGrab":false,"onDownload":true,"onUpgrade":true,"onRename":false,"onSeriesDelete":false,"onEpisodeFileDelete":false,"onEpisodeFileDeleteForUpgrade":false,"onHealthIssue":false,"onApplicationUpdate":false,"supportsOnGrab":false,"supportsOnDownload":true,"supportsOnUpgrade":true,"supportsOnRename":false,"supportsOnSeriesDelete":false,"supportsOnEpisodeFileDelete":false,"supportsOnEpisodeFileDeleteForUpgrade":true,"supportsOnHealthIssue":false,"supportsOnApplicationUpdate":false,"includeHealthWarnings":false,"name":"TdarrScan.bash","fields":[{"name":"path","value":"/config/extended/TdarrScan.bash"},{"name":"arguments"}],"implementationName":"Custom Script","implementation":"CustomScript","configContract":"CustomScriptSettings","infoLink":"https://wiki.servarr.com/sonarr/supported#customscript","message":{"message":"Testing will execute the script with the EventType set to Test, ensure your script handles this correctly","type":"warning"},"tags":[]}')
		log "Complete"
	fi
fi


if [ "$configureCustomFormats" == "true" ] || [ -z "$configureCustomFormats" ]; then
	# Add Language: Not Original Custom Format
	log "Adding Language: Not Original custom format"
	updateArr=$(curl -s "$arrUrl/api/v3/customformat?" -X POST -H "Content-Type: application/json" -H "X-Api-Key: ${arrApiKey}" --data-raw '{"includeCustomFormatWhenRenaming":false,"trash_id":"guide-only","trash_score":"-10000","trash_description":"Language: Original Only","name":"Language: Not Original","specifications":[{"implementation":"LanguageSpecification","implementationName":"Language","infoLink":"https://wiki.servarr.com/sonarr/settings#custom-formats-2","negate":true,"required":false,"fields":[{"order":0,"name":"value","label":"Language","value":-2,"type":"select","advanced":false,"selectOptions":[{"value":-2,"name":"Original","order":0},{"value":0,"name":"Unknown","order":0},{"value":26,"name":"Arabic","order":0},{"value":41,"name":"Bosnian","order":0},{"value":28,"name":"Bulgarian","order":0},{"value":38,"name":"Catalan","order":0},{"value":10,"name":"Chinese","order":0},{"value":39,"name":"Croatian","order":0},{"value":25,"name":"Czech","order":0},{"value":6,"name":"Danish","order":0},{"value":7,"name":"Dutch","order":0},{"value":1,"name":"English","order":0},{"value":42,"name":"Estonian","order":0},{"value":16,"name":"Finnish","order":0},{"value":19,"name":"Flemish","order":0},{"value":2,"name":"French","order":0},{"value":4,"name":"German","order":0},{"value":20,"name":"Greek","order":0},{"value":23,"name":"Hebrew","order":0},{"value":27,"name":"Hindi","order":0},{"value":22,"name":"Hungarian","order":0},{"value":9,"name":"Icelandic","order":0},{"value":44,"name":"Indonesian","order":0},{"value":5,"name":"Italian","order":0},{"value":8,"name":"Japanese","order":0},{"value":21,"name":"Korean","order":0},{"value":36,"name":"Latvian","order":0},{"value":24,"name":"Lithuanian","order":0},{"value":45,"name":"Macedonian","order":0},{"value":29,"name":"Malayalam","order":0},{"value":15,"name":"Norwegian","order":0},{"value":37,"name":"Persian","order":0},{"value":12,"name":"Polish","order":0},{"value":18,"name":"Portuguese","order":0},{"value":33,"name":"Portuguese (Brazil)","order":0},{"value":35,"name":"Romanian","order":0},{"value":11,"name":"Russian","order":0},{"value":40,"name":"Serbian","order":0},{"value":31,"name":"Slovak","order":0},{"value":46,"name":"Slovenian","order":0},{"value":3,"name":"Spanish","order":0},{"value":34,"name":"Spanish (Latino)","order":0},{"value":14,"name":"Swedish","order":0},{"value":43,"name":"Tamil","order":0},{"value":32,"name":"Thai","order":0},{"value":17,"name":"Turkish","order":0},{"value":30,"name":"Ukrainian","order":0},{"value":13,"name":"Vietnamese","order":0}],"privacy":"normal"}],"name":"Not Original Language","id":2}]}')
	log "Complete"
fi

sleep infinity
exit $?
